//
//  UserViewController.swift
//  jiaoyi
//
//  Created by wjk on 2018/7/24.
//  Copyright © 2018年 wjk. All rights reserved.
//

import PPBadgeViewSwift
import SwiftyJSON

class UserViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var availableFundLabel: UILabel!
    @IBOutlet weak var frozenPaymentLabel: UILabel!
    @IBOutlet weak var frozenTradeDepositLabel: UILabel!
    @IBOutlet weak var tempFrozenFundLabel: UILabel!
    
    @IBOutlet weak var labelName: UILabel!
    @IBOutlet weak var tableView: UITableView!
    
    var isRenZheng:Bool = false
    
    var isCa:Bool = false
    
    let datas = [[["name":"会员信息","icon":"会员信息","iden":"UserBaseViewController"]],
                 [["name":"资金流水","icon":"资金流水","iden":"KYDrawerController"],
                  ["name":"出入金记录","icon":"出入金","iden":"UnAmount"]],
//                 [["name":"对账明细","icon":"对账","iden":"QuotedPriceViewController"]],
                 [["name":"我的报价","icon":"报价","iden":"QuotedPriceViewController"],
                  ["name":"我的被报价","icon":"被报价","iden":"QuotedPriceViewController"]],
                 [["name":"设置","icon":"设置","iden":"SettingViewController"]]]
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "个人中心";
        addRightBar()
        
//        NotificationCenter.default.addObserver(self, selector: #selector(fundDetail), name: NSNotification.Name.UserDidLogin, object: nil)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NetWorkRequest(.enterpriseinfo()) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                let data = JSON(res["data"]!)
                self.labelName.text = data["enterprise_name"].stringValue
                (UIApplication.shared.delegate as! AppDelegate).enterprise_id = data["enterprise_id"].intValue
                (UIApplication.shared.delegate as! AppDelegate).enterprise_name = data["enterprise_name"].stringValue
                if data["bank_is_trade"].intValue == 1 &&
                    data["base_is_trade"].intValue == 1 &&
                    data["detail_is_trade"].intValue == 1 &&
                    data["user_is_trade"].intValue == 1
                     {
                        self.isRenZheng = true
                }else {
                    UIAlertController.showAlert(in: self, withTitle: "温馨提示", message: "您的资料还未完善，请先完善资料？", cancelButtonTitle: "取消", destructiveButtonTitle: "确定", otherButtonTitles: nil, tap: { (vc, ac, index) in
                        if index > 0 {
                            self.navigationController?.pushViewController(R.storyboard.user.userBaseViewController()!, animated: true)
                        }
                    })
                }
                
                if data["is_ca"].intValue == 1 {
                    self.isCa = true
                    (UIApplication.shared.delegate as! AppDelegate).isCa = true
                }else {
                    (UIApplication.shared.delegate as! AppDelegate).isCa = false
                }
                 self.tableView.reloadData()
            }
        }
        
        NetWorkRequest(.accountdetail()) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                let data = JSON(res["data"]!)
                let formater = NumberFormatter()
                
                formater.numberStyle = .decimal
                formater.minimumFractionDigits = 2
                formater.maximumFractionDigits = 2
                
                self.availableFundLabel.attributedText = StyledTextBuilder(text: "")
                    .save()
                    .add(text: formater.string(from: NSNumber.init(value: data["available_fund"].doubleValue / 100.0))!, traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.red, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 16)])
                    .restore()
                    .add(text: " 元", traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.black, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14)])
                    .restore()                    
                    .build()
                    .render(contentSizeCategory: .large)
                self.tempFrozenFundLabel.attributedText = StyledTextBuilder(text: "")
                    .save()
                    .add(text: formater.string(from: NSNumber(value:data["temp_frozen_fund"].doubleValue / 100.0))!, traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.red, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 16)])
                    .restore()
                    .add(text: " 元", traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.black, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14)])
                    .restore()
                    .build()
                    .render(contentSizeCategory: .large)
                self.frozenPaymentLabel.attributedText = StyledTextBuilder(text: "")
                    .save()
                    .add(text: formater.string(from: NSNumber(value:data["frozen_payment"].doubleValue / 100.0))!, traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.red, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 16)])
                    .restore()
                    .add(text: " 元", traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.black, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14)])
                    .restore()
                    .build()
                    .render(contentSizeCategory: .large)
                let c = data["frozen_trade_deposit"].doubleValue + data["frozen_perform_deposit"].doubleValue
                self.frozenTradeDepositLabel.attributedText = StyledTextBuilder(text: "")
                    .save()
                    .add(text: formater.string(from: NSNumber(value: c / 100.0))!, traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.red, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 16)])
                    .restore()
                    .add(text: " 元", traits: [.traitBold], attributes: [NSAttributedStringKey.foregroundColor:UIColor.black, NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14)])
                    .restore()
                    .build()
                    .render(contentSizeCategory: .large)
            } else if res["code"] as! String == "100008" {
                
            }
        }
        
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        NetWorkRequest(.unread()) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                let d = jsonFormater(data: res["data"] as Any)
                self.navigationItem.rightBarButtonItem?.pp.addBadge(number: d["unread_count"].intValue)
            }
        }
    }
    
    func addRightBar() {
        let bar = UIBarButtonItem(image: R.image.message(), style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.openMessage(_:)))
        self.navigationItem.rightBarButtonItem = bar
        
    }
    
    @objc func openMessage(_ bar : UIBarButtonItem) {
        let vc = R.storyboard.user.messageViewController()!
        vc.type = 1
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let st = UIStoryboard(name: "Login",bundle: nil)
        let vc = st.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    override func didReceiveMemoryWarning() {        
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count;
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas[section].count;
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserTableViewCell", for: indexPath) as? UserTableViewCell
        let dat = datas[indexPath.section][indexPath.row];
        cell?.imgIcon.image = UIImage(named: dat["icon"]!)
        cell?.labelTitle.text = dat["name"]!
        if indexPath.section==0 && (self.isRenZheng == false || self.isCa == false) {
            cell?.labelStatus.isHidden = false
            if self.isRenZheng == false {
                cell?.labelStatus.text = "资料未完善，无法交易"
            }else {
                cell?.labelStatus.text = "实名未完成，无法交易"
            }
        }else {
            cell?.labelStatus.isHidden = true
        }
        return cell!;
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true);
        
        let iden = datas[indexPath.section][indexPath.row]["iden"]
        
        let vc = R.storyboard.user().instantiateViewController(withIdentifier: iden!)
        vc.title = datas[indexPath.section][indexPath.row]["name"]
        self.navigationController?.pushViewController(vc, animated: true);
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
